package com.learn.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
@Component
@Slf4j
public class WxUtils {


     String appId = "wx8b002bb30a8ebfcf";
     String secret = "619cdd6359c3f641fba273d6b8fe06b9";
     String notifyUrl = "http://anwnkt.natappfree.cc/pay/mpNotifyUrl";

    public  String getOpenIdOrUnionId(String code,@RequestParam(defaultValue = "unionid") String type)  {

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String body = HttpRequest.get(url).execute().body();
        Map<String, Object> bean = JSONUtil.toBean(body, HashMap.class);

        Object o = bean.get("openid");
        Object o1 = bean.get("unionid");

        if (o == null || o1 == null) {
            String msg = bean.get("errmsg").toString();
            log.error(msg);
        }

        if (type.equals("unionid")) {
            return o1.toString();
        }
        return o.toString();
    }


    // 实现给微信公众号发送消息
    public String sendMessage(String message,String openId){



        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getAccessToken();

        Map<String, Object> data = new HashMap<>();
        data.put("touser", openId);
        data.put("template_id", "jn-ew4MvjZ0DnlB_odvJyq49pAp1OBno4nqylYp9n5E"); // 替换为你申请到的正式 TemplateID
        data.put("url", ""); // 可选：点击跳转链接

       // 这里的参数需要填写，根据实际情况进行修改
        Map<String, Object> params = new HashMap<>();
        params.put("product_name", Map.of("value", message+"商品"));
        params.put("delivery_content", Map.of("value", message+"简介"));
        params.put("send_time", Map.of("value", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm"))));
        params.put("remark", Map.of("value", "商品备注信息"));

        data.put("data", params);
        String body = HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(data))
                .execute().body();

        return  "";
    }

    private String getAccessToken() {

        String mpAppId="wxbdba097ecaa2f9f0";
        String mpSecret="a377d31678aba42d6720958d37227476";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + mpAppId + "&secret=" + mpSecret;
        String body = HttpRequest.get(url).execute().body();
        return JSONUtil.parseObj(body).getStr("access_token");

    }


}
